package com.jt.assistant.ui

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Vibrator
import cn.bingoogolapple.qrcode.core.BarcodeType
import cn.bingoogolapple.qrcode.core.QRCodeView
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.jt.assistant.R
import com.jt.assistant.base.GlobalConfig.SCAN_LABEL
import com.jt.assistant.base.GlobalConfig.SCAN_TYPE_ONESHOT
import com.jt.assistant.base.GlobalConfig.SCAN_TYPE_RECEIVE
import com.yzp.mvvmlibrary.base.BaseActivity
import com.yzp.mvvmlibrary.base.MessageEvent
import com.yzp.mvvmlibrary.base.NoViewModel
import kotlinx.android.synthetic.main.activity_decode.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

/**
 * 二维码扫描界面
 */
class DecodeActivity : BaseActivity<NoViewModel>(), QRCodeView.Delegate {

    override fun layoutId(): Int = R.layout.activity_decode

    override fun initView(savedInstanceState: Bundle?) {
    }

    override fun initData() {
        zbar_view.setDelegate(this)
    }

    override fun initListener() {
    }

    override fun onStart() {
        super.onStart()
        GlobalScope.launch {
            delay(100)
            zbar_view.startCamera() // 打开后置摄像头开始预览，但是并未开始识别
            zbar_view.changeToScanBarcodeStyle() // 切换成扫描条码样式
            zbar_view.setType(BarcodeType.ALL, null) // 识别所有类型的码
            zbar_view.startSpotAndShowRect() // 显示扫描框，并开始识别
        }

    }

    override fun onStop() {
        zbar_view.stopCamera() // 关闭摄像头预览，并且隐藏扫描框
        super.onStop()
    }

    override fun onDestroy() {
        zbar_view.onDestroy() // 销毁二维码扫描控件
        super.onDestroy()
    }

    private fun vibrate() {
        val vibrator: Vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(400)
    }

    override fun onScanQRCodeSuccess(result: String?) {
        if (!result.isNullOrEmpty()) {
            log(result)
            vibrate()
            activityResult(result)
        }
    }

    override fun onCameraAmbientBrightnessChanged(isDark: Boolean) {
    }

    override fun onScanQRCodeOpenCameraError() {
        showDialog()
    }

    @SuppressLint("SetTextI18n")
    private fun activityResult(result: String) {
        EventBus.getDefault().post(
            MessageEvent(
                intent.getStringExtra("SCAN_TYPE").toString(),
                result
            )
        )


        if (intent.getStringExtra("SCAN_TYPE")
                .toString() == SCAN_TYPE_ONESHOT || intent.getStringExtra("SCAN_TYPE")
                .toString() == SCAN_TYPE_RECEIVE
        ) {
            finish()
        } else {
            tv_scanResult.text = result
            GlobalScope.launch {
                delay(800)
                zbar_view.startSpot()
            }
        }

    }

    private fun showDialog() {
        MaterialDialog(this).show {
            title(null, "相机打开失败,请授予相关权限")
            cornerRadius(8f)
            positiveButton(null, "确定") {
                finish()
                dismiss()
            }
            negativeButton(null, "取消") {
                dismiss()
            }
            lifecycleOwner(this@DecodeActivity)
        }
    }

}